package com.ndkj.consumer.service.consumer;

import com.ndkj.providercommon.client.ProviderService;
import com.ndkj.rpcserver.common.dto.Invocation;
import com.ndkj.rpcserver.common.utils.HttpClient;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.stream.Collectors;

public class Consumer {

    /**目标调用方法*/
    private static final String TARGET_METHOD = "doSome";

    /**目标调用方法版本号*/
    private static final String TARGET_METHOD_VERSION = "1.0.0";

    /**RPC SERER主机*/
    private static final String RPC_SERVER_HOST= "localhost";

    /**RPC SERER端口*/
    private static final Integer RPC_SERVER_PORT = 8080;

    /**
     * Step 2
     * 发起RPC调用
     */
    public static void main(String[] args) {
        Object[] objects = {"miaoliu"};
        String res = (String) rpcCall(RPC_SERVER_HOST, RPC_SERVER_PORT, TARGET_METHOD, ProviderService.class, TARGET_METHOD_VERSION, objects);
        System.out.println(res);
    }

    /**
     * 伪代理调用
     */
    public static Object rpcCall(String rpcServerHost, Integer rpcServerPort, String targetMethod, Class interfaceClazz, String version, Object[] args) {
        Method method = Arrays.stream(interfaceClazz.getMethods()).filter(e -> e.getName().equals(targetMethod)).collect(Collectors.toList()).get(0);
        Class<?>[] parameterTypes = method.getParameterTypes();

        Invocation invocationDTO = new Invocation(ProviderService.class.getName(), targetMethod, version, parameterTypes, args);
        HttpClient httpClient = new HttpClient();
        return httpClient.send(rpcServerHost, rpcServerPort, invocationDTO);
    }

}
